// dart_control_flow_demonstration.dart
// 需要 Dart 3.0 或更高版本

import 'dart:math';

// 密封类示例（支持 Exhaustiveness 检查）
sealed class Shape {}

class Square implements Shape {
  final double length;
  Square(this.length);
}

class Circle implements Shape {
  final double radius;
  Circle(this.radius);
}

void main() {
  // if-case 示例
  (Object? pair) {
    if (pair case [int x, int y]) {
      print('坐标点: ($x, $y)');
    } else {
      throw FormatException('无效坐标格式');
    }
  }([10, 20]); // 测试输入

  // switch 语句示例
  String command = 'OPEN';
  switch (command) {
    case 'CLOSED':
      print('执行 CLOSED 操作');
      break;
    case 'OPEN':
      print('执行 OPEN 操作');
      continue shared; // 跳转到标签
    shared:
    case 'PENDING':
      print('执行 PENDING/OPEN 共享操作');
  }

  // switch 表达式示例
  int charCode = 43; // '+' 的 ASCII 码
  var token = switch (charCode) {
    43 || 45 || 42 || 47 => '运算符',
    44 || 59 => '标点符号',
    >= 48 && <= 57 => '数字',
    _ => throw FormatException('无效字符'),
  };
  print('识别到: $token');

  // 密封类与 Exhaustiveness 检查
  Shape shape = Circle(5);
  print('面积: ${calculateArea(shape)}');
}

// 使用 switch 表达式处理密封类
double calculateArea(Shape shape) => switch (shape) {
  Square(length: var l) => l * l,
  Circle(radius: var r) => pi * r * r,
};

// Guard 子句示例
void guardClauseExample(int value) {
  switch (value) {
    case > 100 when value.isEven:
      print('大于100的偶数');
    case > 100:
      print('大于100的奇数');
    case _ when value == 42:
      print('答案是42');
    default:
      print('其他情况');
  }
}
